use yew::prelude::*;

pub struct Model {
    value: isize,
    onincrement: Callback<isize>,
    ondecrement: Callback<isize>,
}

#[derive(Properties)]
pub struct Props {
    #[props(required)]
    pub value: isize,
    #[props(required)]
    pub onincrement: Callback<isize>,
    #[props(required)]
    pub ondecrement: Callback<isize>,
}

pub enum Msg {
    Increment,
    Decrement,
}

impl Component for Model {
    type Message = Msg;
    type Properties = Props;

    fn create(props: Self::Properties, _: ComponentLink<Self>) -> Self {
        Model {
            value: props.value,
            onincrement: props.onincrement,
            ondecrement: props.ondecrement,
        }
    }

    fn update(&mut self, msg: Self::Message) -> ShouldRender {
        match msg {
            Msg::Increment => self.onincrement.emit(self.value),
            Msg::Decrement => self.ondecrement.emit(self.value),
        }
        true
    }

    fn change(&mut self, props: Self::Properties) -> ShouldRender {
        self.value = props.value;
        self.onincrement = props.onincrement;
        self.ondecrement = props.ondecrement;
        true
    }
}

impl Renderable<Model> for Model {
    fn view(&self) -> Html<Self> {
        html! {
            <div class="field has-addons">
                <p class="control">
                    <button class="button" onclick=|_| Msg::Decrement>
                        {"Decrement"}
                    </button>
                </p>
                <p class="control">
                    <input class="input has-text-centered" type="text" value=self.value readonly=true />
                </p>
                <p class="control">
                    <button class="button" onclick=|_| Msg::Increment>
                        {"Increment"}
                    </button>
                </p>
            </div>
        }
    }
}
